package generic;

import java.util.ArrayList;

/**
 * Created by Terry
 * Description:
 *  写一个泛型类，求泛型数组当中的最大值。
 * User: GAOBO
 * Date: 2021-07-27
 * Time: 9:44
 */

class Algorithm<T extends Comparable<T>> {
    public T findMax(T[] array) {
        T max = array[0];
        for (int i = 1; i < array.length; i++) {
            //max < array[i]
            if(max.compareTo(array[i]) < 0) {
                max = array[i];
            }
        }
        return max;
    }
}

class Algorithm2 {
    //泛型方法
    public static<T extends Comparable<T>> T findMax(T[] array) {
        T max = array[0];
        for (int i = 1; i < array.length; i++) {
            if(max.compareTo(array[i]) < 0) {
                max = array[i];
            }
        }
        return max;
    }
}


class Test {

    public static<T> void print(ArrayList<T> list) {

        for (T t : list) {
            System.out.println(t);
        }
    }

    //代表通配符  擦除机制  Object
    public static void print2(ArrayList<?> list) {
        for (Object t : list) {
            System.out.println(t);
        }
    }
}


public class TestDemo2 {

    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        Test.print(list);
        System.out.println("===============");
        Test.print2(list);

    }

    public static void main2(String[] args) {
        Integer[] integers = {1,2,13,4,5};
        //会根据 形参的类型 推导出 整个泛型的类型参数
        Integer ret = Algorithm2.findMax(integers);
        System.out.println(ret);
        //一般这个就省略了
        Integer ret2 = Algorithm2.<Integer>findMax(integers);
        System.out.println(ret2);
    }

    public static void main1(String[] args) {
        Algorithm<Integer> algorithm1 = new Algorithm<>();
        Integer[] integers = {1,2,13,4,5};
        Integer ret = algorithm1.findMax(integers);
        System.out.println(ret);
        Algorithm<String> algorithm2 = new Algorithm<>();
    }
}
